package com.chaos.system.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chaos.framework.model.dto.ID;
import com.chaos.framework.model.dto.page.PageList;
import com.chaos.framework.model.dto.page.PageQueryDto;
import com.chaos.framework.model.dto.result.data.DataResult;
import com.chaos.framework.model.entity.Table;
import com.chaos.framework.model.helper.ConvertHelper;
import com.chaos.framework.model.helper.PageHelper;
import com.chaos.system.api.data.TUserData;
import com.chaos.system.entity.UserSessionKey;
import com.chaos.system.api.data.UserSessionKeyData;
import com.chaos.system.mapper.UserSessionKeyMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author jacky
 * @since 2025-07-03
 */
@Slf4j
@Component
public class UserSessionKeyService extends ServiceImpl<UserSessionKeyMapper, UserSessionKey> {

    public ID insertModel(UserSessionKeyData data) {
        UserSessionKey entity = ConvertHelper.convert(data, UserSessionKey.class);
        return save(entity) ? new ID(entity.getId()) : null;
    }

    public boolean deleteModel(ID data) {
        return removeById(data.getId());
    }

    public boolean updateModelByID(UserSessionKeyData data) {
        UserSessionKey entity = ConvertHelper.convert(data, UserSessionKey.class);
        return update(entity, new UpdateWrapper<UserSessionKey>().eq(Table.ID, data.getId()));
    }

    public UserSessionKeyData selectByID(ID data) {
        return ConvertHelper.convert(getOne(new QueryWrapper<UserSessionKey>().eq(Table.ID, data.getId())),
                UserSessionKeyData.class);
    }

    public List<UserSessionKeyData> selectByData(UserSessionKeyData data) {
        LambdaQueryWrapper<UserSessionKey> query = new LambdaQueryWrapper<>();
        query.eq(!ObjectUtil.isEmpty(data.getId()), UserSessionKey::getId, data.getId());
        query.orderByDesc(UserSessionKey::getId);
        return ConvertHelper.convert(list(query), UserSessionKeyData.class);
    }

    public PageList<UserSessionKeyData> selectByPage(PageQueryDto<UserSessionKeyData> pageData) {

        UserSessionKeyData data = pageData.getData();
        LambdaQueryWrapper<UserSessionKey> query = new LambdaQueryWrapper<>();
        query.eq(!ObjectUtil.isEmpty(data.getId()), UserSessionKey::getId, data.getId());
        query.orderByAsc(UserSessionKey::getId);

        return PageHelper.pageList(page(PageHelper.page(pageData), query), UserSessionKeyData.class);
    }

    public String selectLatestSessionKeyByUserId(Long userId) {
        return baseMapper.selectLatestSessionKeyByUserId(userId);
    }
}
